package com.micro.service.auth.server.login;

import com.micro.service.account.share.dto.UserBaseDto;
import com.micro.service.account.share.service.UserBaseService;
import com.micro.service.common.dto.ResultDTO;
import com.micro.service.common.enums.UserStatusEnum;
import com.micro.service.common.utils.HttprequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author lvxiucai
 * @description 退出功能
 * @date 2019/9/9
 */
@RestController
@Slf4j
public class LogoutController {

    private RestOperations restTemplate = new RestTemplate();
    @Value("${checkTokenUrl}")
    private String checkTokenEndpointUrl;
    @Autowired
    private ConsumerTokenServices consumerTokenServices;

    @Autowired
    private UserBaseService userBaseService;

    @RequestMapping("/logout")
    public ResultDTO<Boolean> logout(HttpServletRequest request, HttpServletResponse response){
        ResultDTO<Boolean> resultDTO = new ResultDTO<>();
        Map<String,Object> requestMap = HttprequestUtils.getRequestMap(request);
        String accessToken = (String)requestMap.get("token");
        if(StringUtils.isNotBlank(accessToken)){
            if(consumerTokenServices.revokeToken(accessToken)){
                return resultDTO.success(true);
            }
            return resultDTO.success(false);
        }else{
            return resultDTO.failure("token为空！");
        }
    }

    @RequestMapping("/withdraw")
    public ResultDTO<Boolean> withdraw(HttpServletRequest request, HttpServletResponse response){
        ResultDTO<Boolean> resultDTO = new ResultDTO<>();
        Map<String,Object> requestMap = HttprequestUtils.getRequestMap(request);
        UserBaseDto requestDto = new UserBaseDto();
        //获取入参用户id
        String idStr = requestMap.get("id")==null?null:requestMap.get("id").toString();
        if(StringUtils.isBlank(idStr)){
            return resultDTO.failure("id不能为空");
        }
        String accessToken = (String)requestMap.get("token");
        if(StringUtils.isBlank(accessToken)){
            return resultDTO.failure("token为空！");
        }
        MultiValueMap<String, String> formData = new LinkedMultiValueMap();
        formData.add("token", accessToken);
        HttpHeaders headers = new HttpHeaders();
        Map<String,Object> map = postForMap(checkTokenEndpointUrl,formData,headers);
        if(map == null|| !map.containsKey("active") && !"true".equals(String.valueOf(map.get("active")))){
            return resultDTO.failure("token无效");
        }
        //获取token中用户id
        String idFromToken = map.get("userId")!=null ? map.get("userId").toString() : null;
        if(!idStr.equals(idFromToken)){
            log.error("用户非法注销,idStr:{},idFromToken:{}",idStr,idFromToken);
            return resultDTO.failure("用户非法");
        }
        requestDto.setId(Long.parseLong(idFromToken));
        requestDto.setStatus(UserStatusEnum.IS_DEL.getStatus());
        ResultDTO<Boolean> updateRes = userBaseService.updateUserBase(requestDto);
        //更新成功
        if(updateRes != null && updateRes.isSuccess() && updateRes.getData()){
            //清除该账户token
            boolean removeToken = consumerTokenServices.revokeToken(accessToken);
            return resultDTO.success(true);
        }

        return resultDTO.success(false);

    }

    //根据token获取用户信息
    private Map<String, Object> postForMap(String path, MultiValueMap<String, String> formData, HttpHeaders headers) {
        if(StringUtils.isEmpty(path)){
            return null;
        }
        Map map = (Map)this.restTemplate.exchange(path, HttpMethod.POST, new HttpEntity(formData, headers), Map.class, new Object[0]).getBody();
        return map;
    }




}
